﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using Jumpton.SFA.Server.Entity;
using Jumpton.SFA.Server.BusinessRule.MasterData;
using Jumpton.SFA.Server.BusinessRule.System;
using Jumpton.SFA.Server.BusinessRule;

using Jumpton.Persistent;
using BusinessRule.System;
using System.Collections.Generic;

public partial class System_Edit_User : PageBase
{
    private UserManager usermanager;
    private OrgainzationManager orgManager = new OrgainzationManager();

    protected String DefaultPassword;

    protected void Page_Load(object sender, EventArgs e)
    {

        if (!IsPostBack)
        {
            BindGroup();
            DefaultPassword = new ConfigManager().GetSystemConfig(ConfigEnum.DEFAULT_PASSWORD, ConfigEnum.SUB_KEY001, MyStateManager.DomainID).Value;
            this.DataBind();
            if (!string.IsNullOrEmpty(Request["id"]))
            {
                usermanager = new UserManager();
                USERS user = usermanager.GetUserByID(decimal.Parse(Request["id"]));

                txtName.Text = user.CODE;
                txtName.Enabled = false;
                cbxValid.Checked = user.ACTIVE;

                using (DataTable dt = new UserRoleManager().GetRoleWithUser(user.ID, user.DOMAINID, true))
                {
                    foreach (ListItem item in ddlGroup.Items)
                    {
                        if (dt.Select("id=" + item.Value).Length > 0)
                            item.Selected = true;
                    }
                }



                Person person = new PersonManager().Load(Int32.Parse(user.PERSONID.ToString()));

                if (person != null)
                {
                    ddlPerson.Items.Clear();
                    ddlPerson.Items.Add(new ListItem(person.Name, person.ID.ToString()));
                    ddlPerson.Enabled = false;
                    if (!user.ACTIVE)
                    {
                        ddlPerson.Items.Insert(0, new ListItem(person.Name, person.ID.ToString()));
                    }
                    else
                    {
                        ddlPerson.SelectedValue = person.ID.ToString();
                    }
                    ddlPerson.Enabled = false;

                    txtHidOrg.Value = person.OrgID.ToString();

                    if (person.Type == 2)
                    {
                        ddlChains.Visible = false;
                        txt_Chains.Visible = false;
                        txtOrg.Text = new ThirdPartyCompaniesManager().Load(person.OrgID).NAME;
                        this.ddlCity.Visible = true;
                        //加载城市信息
                        BindDDLCity();

                        String thridorgId = "";
                        try
                        {
                            //thridorgId = new UserManager().GetUserByPersonID(person.ID).THRIDORGMEMBERID.ToString();
                        }
                        catch
                        {
                            //thridorgId = "-1";
                        }
                        ddlCity.SelectedValue = thridorgId;
                    }
                    else
                    {
                        txtOrg.Text = orgManager.Load(person.OrgID).NAME;
                    }
                    ddlChains.DataSource = new ChainManager().GetCourseTable(MyStateManager.DomainID, person.OrgID);
                    ddlChains.DataTextField = "DESCRIPTION";
                    ddlChains.DataValueField = "ID";
                    ddlChains.DataBind();
                    ddlChains.Items.Insert(0, new ListItem("--请选择--", ""));
                    try
                    {
                        ddlChains.SelectedValue = usermanager.LoadChainsByUser(user.ID).CHAINSID.ToString();
                    }
                    catch
                    {

                    }
                }
            }
            else
            {
                if (MyStateManager.UserLevel == 2)
                {
                    BindPerson(MyStateManager.UserLevel);
                }
                else
                {
                    BindPerson(10);
                }

            }

        }
    }

    protected int getIndex(DropDownList ddl, string value)
    {
        int index = -1;
        foreach (ListItem li in ddl.Items)
        {
            index++;
            if (li.Value.Equals(value))
            {
                return index;
            }

        }
        return index;
    }

    #region 绑定人员信息
    private void BindPerson(Byte person_type)
    {
        List<Person> plist = new List<Person>();
        if (person_type == 2)
        {
            DataTable dt1 = new PersonManager().GetPersonByThridPartyCom(MyStateManager.DomainID, 0);
            foreach (DataRow item in dt1.Rows)
            {
                Person p = new Person();
                p.ID = Convert.ToInt32(item[0]);
                p.Name = item[1].ToString();
                plist.Add(p);
            }
            ddlChains.Visible = false;
            txt_Chains.Visible = false;
        }
        else
        {
            DataTable dt = new PersonManager().GetPersonByDomain(MyStateManager.DomainID, MyStateManager.OrgID, MyStateManager.PersonID, !string.IsNullOrEmpty(Request["id"]), 1);
            foreach (DataRow item in dt.Rows)
            {
                Person p = new Person();
                p.ID = Convert.ToInt32(item[0]);
                p.Name = item[1].ToString();
                plist.Add(p);
            }
            DataTable dt1 = new PersonManager().GetPersonByThridPartyCom(MyStateManager.DomainID, 0);
            foreach (DataRow item in dt1.Rows)
            {
                Person p = new Person();
                p.ID = Convert.ToInt32(item[0]);
                p.Name = item[1].ToString();
                plist.Add(p);
            }
        }
        ddlPerson.DataSource = plist;
        ddlPerson.DataBind();
        ddlPerson.Items.Insert(0, new ListItem("----请选择----", ""));
    }
    #endregion

    #region 绑定用户组
    private void BindGroup()
    {
        decimal userid = 0;
        decimal.TryParse(Request["id"], out userid);
        DataTable dt = new GroupManager().LoadWithRecursion(MyStateManager.DomainID, MyStateManager.GroupID, MyStateManager.UserLevel, 1);

        ddlGroup.DataSource = dt;
        ddlGroup.DataTextField = "CODE";
        ddlGroup.DataValueField = "ID";
        ddlGroup.DataBind();

    }
    #endregion



    #region 提交
    protected void btnSave_Click(object sender, EventArgs e)
    {
        bool noselected = false;
        foreach (ListItem lt in ddlGroup.Items)
        {
            if (lt.Selected)
            {
                noselected = true;
            }
        }
        if (!noselected)
        {
            this.ShowMessage("请选择角色");
            return;
        }


        string userName = txtName.Text.Trim().Replace("'", "");
        decimal personID = ddlPerson.SelectedValue == "" ? 0 : decimal.Parse(ddlPerson.SelectedValue);
        Person person = new PersonManager().Load(personID);


        decimal groupID = decimal.Parse(ddlGroup.SelectedValue);
        USERS user = null;
        usermanager = new UserManager();
        //新增
        if (string.IsNullOrEmpty(Request["id"]))
        {
            //判断是否存在同名帐号
            if (UserManager.IsExistsUser(txtName.Text.Trim()))
            {
                ShowMessage("已存在该用户帐号");

                return;
            }
            user = new USERS();
            user.CODE = userName;

            //从配置表读取默认密码
            string defaultPwd = new ConfigManager().GetSystemConfig(ConfigEnum.DEFAULT_PASSWORD, ConfigEnum.SUB_KEY001, MyStateManager.DomainID).Value;

            user.PASSWORD = Jumpton.Common.Functions.EncryptString(defaultPwd);
            user.UserToken = Jumpton.Common.Functions.EncryptString(userName + defaultPwd);
        }
        else
        {
            user = usermanager.GetUserByID(decimal.Parse(Request["id"]));

            if (new MobileUserManager().Load(user.ID, MyStateManager.DomainID) != null && !cbxValid.Checked)
            {
                this.ShowAndRedirect(this, "操作失败:\\n    请先除去帐号【" + user.CODE + "】与巡店督导的关联!", Request.RawUrl);
                return;
            }
            if (new UserManager().GetUserByPersonID(personID) != null && cbxValid.Checked && !user.ACTIVE)
            {
                this.ShowAndRedirect(this, "操作失败:\\n    此用户已经存在关联的帐号!", Request.RawUrl);
                return;

            }
        }
        user.DOMAINID = MyStateManager.DomainID;
        if (!cbxValid.Checked)
            user.PERSONID = 0;
        else
            user.PERSONID = personID;
        user.LAST_UPDATER = MyStateManager.Name;
        user.LAST_UPDATE_TIME = BusinessLogic.GetDateTimeDecimal(DateTime.Now);
        user.FORCEEXPORTALL = "N";
        user.GROUPID = groupID;
        user.ISLOCK = false;
        user.FAILLOGINCOUNT = "0";
        user.ORGID = int.Parse(txtHidOrg.Value.Replace("'", ""));
        user.ACTIVE = cbxValid.Checked;
        user.KIND = "1";
        user.TYPE = person.Type;
        user.USERTYPE = 0;//修改账户类型时同时去掉已有的类型
        if (person.Type == 2)
        {

            //判断执行公司是否存在区域信息，如果不存在提示先维护执行公司和区域信息
            if (ddlCity.SelectedValue == "")
            {
                this.ShowMessage("执行公司区域信息为空，请先维护执行公司区域信息");
                return;
            }

            //user.THRIDORGMEMBERID = Convert.ToInt32(ddlCity.SelectedValue);
        }

        //保存
        usermanager.Save(user);
        user = usermanager.GetUserByCode(user.CODE);

        UserRoleManager manager = new UserRoleManager();
        //保存用户组
        manager.Delete(user.ID);
        foreach (ListItem item in ddlGroup.Items)
        {
            UserRole role = manager.Load(user.ID, decimal.Parse(item.Value));
            if (role == null)
            {
                if (!item.Selected)
                    continue;
                role = new UserRole();
                role.RoleNo = decimal.Parse(item.Value);
                role.UserID = user.ID;
            }

            role.LAST_UPDATER = MyStateManager.Name;
            role.LAST_UPDATE_TIME = BusinessLogic.GetDateTimeDecimal(DateTime.Now);
            role.ACTIVE = item.Selected;
            manager.Save(role);
        }

        if (user.KIND == "1")
        {
            //插入mobileuser
            MobileUserManager moblemanager = new MobileUserManager();
            MOBILE_USERS mobileUser;
            //新增
            if (string.IsNullOrEmpty(Request["id"]))
            {
                mobileUser = new MOBILE_USERS();
                mobileUser.USERID = user.ID;


            }
            //编辑
            else
            {
                mobileUser = moblemanager.Load(decimal.Parse(Request["id"]), MyStateManager.DomainID);
                if (mobileUser == null)
                {
                    mobileUser = new MOBILE_USERS();
                    mobileUser.USERID = decimal.Parse(Request["id"]);


                }
            }
            mobileUser.TYPE = user.TYPE;
            //mobileUser.USERPRODLISTID = decimal.Parse(ddlUserDistributor.SelectedValue);
            mobileUser.DFTYPE = 0;
            mobileUser.DOMAINID = MyStateManager.DomainID;


            if (!moblemanager.Save(mobileUser))
            {
                ShowMessage("保存出错!");
                return;
            }
        }


        try
        {
            if (ddlChains.SelectedValue != string.Empty && ddlChains.Visible)
                usermanager.AddChainsForUser(user.ID, int.Parse(ddlChains.SelectedValue), MyStateManager.Name);
            Response.Redirect("User_List.aspx");
        }
        catch (Exception ex)
        {
            Jumpton.SFA.Server.BusinessRule.System.EventManager.CreateNewEvent(
                 Jumpton.SFA.Server.BusinessRule.System.LogType.GENERAL_EXCEPTION, this.MyStateManager.Name,
                 this.MyStateManager.UserID, "用户保存 - 自定义配置异常:" + ex.Message);
        }
    }
    #endregion



    protected void ddlPerson_SelectedIndexChanged(object sender, EventArgs e)
    {
        try
        {
            Person person = new PersonManager().Load(Int32.Parse(ddlPerson.SelectedValue));
            txtHidOrg.Value = person.OrgID.ToString();
            if (person.Type == 1) //部门
            {
                txtOrg.Text = orgManager.Load(person.OrgID).NAME;
                td_zzjg.Visible = true;
                txt_Chains.Visible = true;
                ddlChains.Visible = true;
                ddlCity.Visible = false;
            }
            else if (person.Type == 2)    //绑定执行公司
            {
                ThirdPartyCompaniesManager tpcManager = new ThirdPartyCompaniesManager();
                txtOrg.Text = tpcManager.Load(person.OrgID).NAME;
                txt_Chains.Visible = false;
                ddlChains.Visible = false;
                ddlCity.Visible = true;
                //加载城市信息
                BindDDLCity();
            }

            ddlChains.DataSource = new ChainManager().GetCourseTable(MyStateManager.DomainID, person.OrgID);
            ddlChains.DataTextField = "DESCRIPTION";
            ddlChains.DataValueField = "ID";
            ddlChains.DataBind();
            ddlChains.Items.Insert(0, new ListItem("--请选择--", ""));

        }
        catch
        {
        }
    }

    public void BindDDLCity()
    {

        
    }
    protected void ddlGroup_SelectedIndexChanged(object sender, EventArgs e)
    {
        if (ddlGroup.SelectedItem != null)
        {
            ListItem lt = ddlGroup.Items.FindByText("经销商");
            if (lt != null)
            {
                this.chains.Visible = lt.Selected;
            }
        }
    }

}
